package com.ly.mpayment.rest.up.yixinyou;

import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Path("yixinyou")
public class YiXinYouRest {

        static Logger logger = Logger.getLogger(YiXinYouRest.class);

        public static final String version = "h1.1";

        @Autowired
        IUporderService upOrderService;

        @Autowired
        IDownRechargeFlowService flowService;

        @Autowired
        IDownShopInfoService shopService;


        @SuppressWarnings("-access")
        @GET
        @Path("callBack")
        public synchronized String callBack(@QueryParam("usr")String usr,@QueryParam("ord")String ord,
                                            @QueryParam("state")String state,@QueryParam("bz")String bz,
                                            @QueryParam("sgn")String sgn){
            logger.info("yixinyou_callBack:"+ord+",state:"+state);
            if(!StringUtils.isBlank(ord) && !StringUtils.isBlank(state)){
                try {
                        UpOrder order = upOrderService.findById(ord);
                        if(state.equals("1") && order != null && order.getStatus() == Config.status[0]){
                            order.setRemark(bz == null ? "" : bz);
                            RechargeRest.successUpOrder.add(order);
                        }else if(state.equals("2") && order != null && order.getStatus() == Config.status[0]){
                            order.setRemark(bz == null ? "" : bz);
                            RechargeRest.failtUpOrder.add(order);
                        }else{
                            logger.info("yixinyou_not_found_order:"+ord);
                        }
                    return "OK";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return "falit";
        }

        public void commitOrder(UpOrder order, UpShopInfo shop) {
            try {
                UpOrder product = upOrderService.findOrderProduct(order.getUporderuuid());
                if (product != null) {
                    com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
                    object.put("usr",shop.getAppId());
                    object.put("ord",order.getUporderuuid());
                    object.put("mob",order.getUpphonenum());
                    object.put("amt",product.getUpShopPro().getUpfacevalue());
                    object.put("tim",new DateUtils().toTimeStamp());
                    object.put("yysid","0");
                    object.put("hmlx","0");
                    //MD5(usr+ord+mob+amt+tim+key)转大写 key为密钥
                    object.put("sgn",MD5.md5(shop.getAppId()+order.getUporderuuid()+order.getUpphonenum()+
                            product.getUpShopPro().getUpfacevalue()+object.getString("tim")+shop.getUpkey()).toUpperCase());
                    String result = HttpClient.httpGetUrl(shop.getOrderCommitAddress().concat("?")+StringSort.jsonToString(object));
                    logger.info("yixinyou_charge_result:"+result+","+StringSort.jsonToString(object));
                    if (!StringUtils.isBlank(result)) {
                        try{
                            //0|提交成功|70.00
                            String res [] = result.split("\\|");
                            if(res.length >= 2 && res[0].equals("1")){
                                this.upOrderService.updateUpOrderMsg(order, res[0],res[1]);
                            }else if (res.length >= 2 && errorCode.contains(res[0])) {
                                order.setRemark(res[1]);
                                RechargeRest.failtUpOrder.add(order);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            upOrderService.updateUpOrderArtificial(order, "",result);
                        }
                    } else {
                        this.upOrderService.updateUpOrderArtificial(order, "",result);
                        logger.info("commityixinyou_error" + order.getUpphonenum());
                    }
                }else{
                    logger.info("commityixinyou error not found product" + order.getUporderuuid());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
                this.upOrderService.updateUpOrderArtificial(order, "", Config.commitFailt);
                logger.info("commityixinyou_error+" + order.getUpphonenum());
            }
        }

    public static void main(String[] args) {
        System.out.println("6|暂不支持此商品|0".split("\\|")[1]);
    }

        private Set<String> errorCode = new HashSet(){{
            add("2");
            add("4");
            add("6");
            add("7");
            add("8");
            add("10");
            add("11");
            add("30");
            add("41");
            add("42");
            add("43");
            add("44");
            add("-3");
            add("-4");
            add("-5");
            add("-6");
            add("-7");
            add("-8");
            add("-9");
            add("-11");
            add("-12");
            add("1001");
            add("1002");
            add("1003");

        }};

        public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
            com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
            object.put("usr",shopInfo.getAppId());
            object.put("ord",upOrder.getUporderuuid());
            object.put("sgn",MD5.md5(shopInfo.getAppId()+upOrder.getUporderuuid()+shopInfo.getUpkey()).toUpperCase());
            String result = HttpClient.httpGetUrl(shopInfo.getOrderStatusAddress().concat("?")+StringSort.jsonToString(object));
            logger.info("yixinyou_charge_result:"+result+","+StringSort.jsonToString(object));
            if(result != null && !result.equals("")){
                //|0|123-充值中|流水号:1234567890
                String res [] = result.split("\\|");
                JSONObject json = JSONObject.fromObject(result);
                UpOrder order = upOrderService.findById(json.getString("outtradeno").trim());
                if(res.length >= 4 && res[1].equals("1") && order != null && order.getStatus() == Config.status[0]){
                    order.setRemark(res[3]);
                    RechargeRest.successUpOrder.add(order);
                }else if( res.length >= 4 && res[1].equals("2")  && order != null && order.getStatus() == Config.status[0]){
                    order.setRemark(res[3]);
                    RechargeRest.failtUpOrder.add(order);
                }
            }else{
                logger.info("yixinyou order failt:"+upOrder.getUpphonenum());
            }
        }

    }

